package com.wuye.controller;


import com.wuye.model.User;
import com.wuye.repository.UserRepository;
import com.wuye.web.ST;
import com.wuye.web.SessionHandler;
import com.wuye.web.UserSession;
import com.wuye.weixin.*;
import com.wuye.weixin.util.AesException;
import com.wuye.weixin.util.WXBizMsgCrypt;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiawenlong on 2016/6/16.
 */
@RestController
@RequestMapping("/weixin")
public class WeixinController {
    private Log log = LogFactory.getLog(this.getClass());


    @Autowired
    private SessionHandler sessionHandler;
    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/getAllWeixinUsers.jspx")
    public ModelAndView getAllWeixinUsers() {
        StringBuffer buf = new StringBuffer();
        try {
            QyWeixin weixin = WeixinManager.getWeixin();
            List<QyUser> users = weixin.getQyUserList(1, 1, 1);
            for (QyUser user : users) {
                QyUser u = weixin.getQyUserInfo(user.getUserid());
                buf.append("---insert into wuye_user(user_id,cell_phone,user_name) values('" + u.getUserid() + "','" + u.getMobile() + "','" + u.getName() + "');");
                buf.append("\n");
            }
        } catch (WeixinException e) {
            log.error("=======================获取用户时出现异常============================", e);
        }
        ModelAndView mv = new ModelAndView("jspx/test");
        mv.addObject("weixin", buf.toString());
        return mv;
    }

    @RequestMapping("/syncUsers.jspx")
    public String syncUsers() {
        StringBuffer buf = new StringBuffer();
        try {
            QyWeixin weixin = WeixinManager.getWeixin();
            List<QyDeptment> deptments = weixin.getQyDeptList();
            Map<Integer,String> depts = new HashMap<Integer, String>();
            for(int i=0;i<deptments.size();i++){
                depts.put(deptments.get(i).getId(),deptments.get(i).getName());
            }
            List<QyUser> users = weixin.getQyUserDetailList(1, 1, 1);
            for (QyUser u : users) {
                User user = userRepository.findByUserId(u.getUserid());
                if (null == user) {
                    user = new User();
                    user.setUserId(u.getUserid());
                }
                user.setCellPhone(u.getMobile());
                user.setPassword("123");
                user.setUserName(u.getName());
                user.setDepartment(u.getDepartment().length > 0 ? u.getDepartment()[0] + "" : "");
                user.setDepartmentName(u.getDepartment().length > 0 ? depts.get(u.getDepartment()[0]): "");
                user.setPosition(u.getPosition());
                user.setEmail(u.getEmail());
                user.setWeixinid(u.getWeixinid());
                user.setAvatar(u.getAvatar());
//                    user.setExtattr(u.getExtattr().toString());
                userRepository.save(user);
            }
        } catch (WeixinException e) {
            log.error("=======================获取用户时出现异常============================", e);
        }
        return ST.ok.toJson();
    }

    /**
     * @param msg_signature 微信加密签名
     * @param timestamp     时间戳
     * @param nonce         随机数
     * @param echostr       随机字符串
     */
    @ResponseBody
    @RequestMapping("/coreWeixin.jspx")
    public String coreWeixin(@RequestParam("msg_signature") String msg_signature,
                             @RequestParam("timestamp") String timestamp,
                             @RequestParam("nonce") String nonce,
                             @RequestParam("echostr") String echostr) {
        String corpId = Configuration.getOAuthAppId(), token = Configuration.getToken(), sEncodingAESKey = Configuration.getEcondingAESKey();
        String sEchoStr; //需要返回的明文
        try {
            log.info("coreWeixin.jspx中接收到的参数：msg_signature=" + msg_signature + ";timestamp=" + timestamp + ";nonce=" + nonce + ";echostr=" + echostr);
            log.info("Configuration的参数：corpId=" + corpId + ";token=" + token + ";sEncodingAESKey=" + sEncodingAESKey);
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, sEncodingAESKey, corpId);
            sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp,
                    nonce, echostr);
            log.info("verifyurl echostr: " + sEchoStr);
            return sEchoStr;
        } catch (AesException e1) {
            log.error("", e1);
        }
        return null;
    }

    @RequestMapping("/weixinLogin.jspx")
    public void weixinLogin(@RequestParam("code") String code, @RequestParam("state") String state, HttpSession session, HttpServletResponse response) {
        log.info("微信登陆获取auth_code=" + code);
        try {
            QyWeixin weixin = WeixinManager.getWeixin();
            JSONObject result = weixin.getQyUserInfoByCode(code);
            if (null != result.getString("UserId")) {
                String userId = result.getString("UserId");
                User user = userRepository.findByUserId(userId);
                if (null == user) {
                    QyUser u = weixin.getQyUserInfo(userId);
                    List<QyDeptment> deptments = weixin.getQyDeptList();
                    Map<Integer,String> depts = new HashMap<Integer, String>();
                    for(int i=0;i<deptments.size();i++){
                        depts.put(deptments.get(i).getId(),deptments.get(i).getName());
                    }
                    user = new User();
                    user.setRoom("");
                    user.setDeskPhone("");
                    user.setUserId(u.getUserid());
                    user.setCellPhone(u.getMobile());
                    user.setPassword("123");
                    user.setUserName(u.getName());
                    user.setDepartment(u.getDepartment().length > 0 ? u.getDepartment()[0] + "" : "");
                    user.setDepartmentName(u.getDepartment().length > 0 ? depts.get(u.getDepartment()[0]): "");
                    user.setPosition(u.getPosition());
                    user.setEmail(u.getEmail());
                    user.setWeixinid(u.getWeixinid());
                    user.setAvatar(u.getAvatar());
//                    user.setExtattr(u.getExtattr().toString());
                    userRepository.save(user);
                }
                UserSession us = sessionHandler.getUserSession(session);
                us.setUserId(user.getUserId());
                us.setCellPhone(user.getCellPhone());
                us.setUserName(user.getUserName());
                sessionHandler.saveUserSession(us, session);
            }
            response.sendRedirect(state);
        } catch (WeixinException e) {
            log.error("=======================weixinLogin获取用户时出现异常============================", e);
        } catch (IOException e) {
            log.error("========================跳转报错================================");
        }
    }
}
